package com.oa.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.joneying.common.annotation.CommonService;
import com.joneying.common.web.response.Resp;
import com.oa.admin.dto.KeyAddVO;
import com.oa.admin.dto.KeyUpdateVO;
import com.oa.admin.entity.KeyRecords;
import com.oa.admin.entity.KeyStorageRecords;
import com.oa.admin.service.IKeyRecordsService;
import com.oa.admin.service.IKeyStorageRecordsService;
import com.oa.admin.vo.KeysDetailsVO;
import com.oa.admin.vo.KeysListVO;
import com.oa.core.PageResult;
import com.oa.admin.entity.Key;
import com.oa.admin.mapper.KeyMapper;
import com.oa.admin.service.IKeyService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.oa.core.constant.Constant;
import com.oa.core.enumm.CodeEnum;
import com.oa.core.exception.BusinessException;
import com.oa.core.exception.DataIsEmptyException;
import com.oa.pm.entity.Organization;
import com.oa.pm.service.IOrganizationService;
import com.oa.system.entity.User;
import com.oa.system.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

import static com.oa.core.utils.Validate.validate;

/**
 * <p>
 * 钥匙表 服务实现类
 * </p>
 *
 * @author syb123
 * @since 2019-01-22
 */
@Service
public class KeyServiceImpl extends ServiceImpl<KeyMapper, Key> implements IKeyService {

    private final KeyMapper keyMapper;
    private final IKeyRecordsService keyRecordsService;
    private final IKeyStorageRecordsService keyStorageRecordsService;
    private final IUserService userService;
    private final IOrganizationService organizationService;

    @Autowired
    public KeyServiceImpl(KeyMapper keyMapper, IKeyRecordsService keyRecordsService, IKeyStorageRecordsService keyStorageRecordsService, IUserService userService, IOrganizationService organizationService) {
        this.keyMapper = keyMapper;
        this.keyRecordsService = keyRecordsService;
        this.keyStorageRecordsService = keyStorageRecordsService;
        this.userService = userService;
        this.organizationService = organizationService;
    }

    @Override
    @CommonService
    public PageResult<Key> findList(Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            List<Key> list = keyMapper.findList();
            return new PageResult<>(list);
        } else {
            // 当前页，总条数 构造 page 对象
            Page<Key> page = new Page<>(pageNum, pageSize);
            //查询
            List<Key> list = keyMapper.findList(page);
            return new PageResult<>(list);
        }
    }

    /**
     * 根据id查询
     */
    @Override
    @CommonService
    public Key findKeyById(String id) {
        return keyMapper.findById(id);
    }

    /**
     * 添加钥匙
     *
     * @param keyAddVO
     * @return
     */
    @Override
    @CommonService
    @Transactional
    public Resp addKeys(KeyAddVO keyAddVO) throws BusinessException {

        CheckKeyAddVOParam(keyAddVO);

        //判断钥匙编号是否重复
        List<Key> keysCheck = keyMapper.selectList(new EntityWrapper<Key>().eq("is_deleted", Constant.IS_DELETE_NO).eq("key_num", keyAddVO.getKeyNum()));
        if (CollUtil.isNotEmpty(keysCheck)) {
            throw new BusinessException("钥匙编号不允许重复!");
        }

        Key key = new Key();
        BeanUtils.copyProperties(keyAddVO, key);

        try {
            keyMapper.insert(key);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("添加钥匙失败!");
        }

        return new Resp<String>().success("添加钥匙成功!");
    }

    /**
     * 根据id修改钥匙
     *
     * @param keyUpdateVO
     * @return
     */
    @Override
    @CommonService
    @Transactional
    public Resp updateKeys(KeyUpdateVO keyUpdateVO) throws BusinessException {

        CheckKeyUpdateVOParam(keyUpdateVO);
        Key keyOld = keyMapper.findById(keyUpdateVO.getId());
        User user = userService.selectById(keyOld.getReserveMan());
        keyOld.setReserveDepartment(user.getDepartmentId());
        keyOld.setReserveMan(user.getId());

        if (!StringUtils.isEmpty(keyUpdateVO.getReserveMan())) {
            if (!keyUpdateVO.getReserveMan().equals(keyOld.getReserveMan())) {
                KeyStorageRecords keyStorageRecords = new KeyStorageRecords();
                keyStorageRecords.setKeyId(keyOld.getId());
                keyStorageRecords.setTime(new Date());

                Organization organization = organizationService.selectById(user.getDepartmentId());
                keyStorageRecords.setPeople(user.getName());
                keyStorageRecords.setDepartment(organization.getOrganizationName());
                keyStorageRecordsService.insert(keyStorageRecords);
            }
        }

        BeanUtils.copyProperties(keyUpdateVO, keyOld);

        try {
            keyMapper.updateById(keyOld);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("修改钥匙失败!");
        }

        return new Resp<String>().success("修改钥匙成功!");
    }

    /**
     * 查询钥匙列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @CommonService
    public PageResult<KeysListVO> findKeysList(Integer pageNum, Integer pageSize) throws DataIsEmptyException {
        if (pageNum == null) {
            List<KeysListVO> list = keyMapper.findKeysList();
            if (CollUtil.isEmpty(list)) {
                throw new DataIsEmptyException();
            }
            return new PageResult<>(list);
        } else {
            Page<KeysListVO> page = new Page<>(pageNum, pageSize);
            List<KeysListVO> list = keyMapper.findKeysList(page);
            if (CollUtil.isEmpty(list)) {
                throw new DataIsEmptyException();
            }
            return new PageResult<>(list);
        }
    }

    /**
     * 根据主键id查询钥匙详情
     *
     * @param id
     * @return
     */
    @Override
    public Resp findKeysDetailsById(String id) throws DataIsEmptyException {
        KeysDetailsVO keysDetailsVO = keyMapper.findKeysDetailsById(id);
        if (StringUtils.isEmpty(keysDetailsVO)) {
            throw new DataIsEmptyException();
        }
        List<KeyStorageRecords> keyStorageRecords = keyStorageRecordsService.selectList(new EntityWrapper<KeyStorageRecords>().eq("is_deleted", Constant.IS_DELETE_NO).eq("key_id", keysDetailsVO.getId()));
        keysDetailsVO.setKeyStorageRecordsList(keyStorageRecords);
        return new Resp<KeysDetailsVO>().success(keysDetailsVO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteKey(String id) {
        Key key = new Key();
        key.setId(id);
        key.setIsDeleted(1);
        if(updateById(key)){
            KeyRecords keyRecords = new KeyRecords();
            keyRecords.setIsDeleted(1);
            keyRecordsService.update(keyRecords, new EntityWrapper<KeyRecords>().eq("key_id", id));
            KeyStorageRecords keyStorageRecords = new KeyStorageRecords();
            keyStorageRecords.setIsDeleted(1);
            keyStorageRecordsService.update(keyStorageRecords, new EntityWrapper<KeyStorageRecords>().eq("key_id", id));
            return true;

        }
        return false;
    }

    /**
     * 参数校验
     *
     * @param
     */
    public void CheckKeyUpdateVOParam(KeyUpdateVO keyUpdateVO) throws BusinessException {
        if (!StringUtils.isEmpty(keyUpdateVO)) {
            List<String> validate = validate(keyUpdateVO);
            if (CollUtil.isNotEmpty(validate)) {
                throw new BusinessException(CodeEnum.PARAMETERS_OF_THE_ABNORMAL.getCode(), validate.toString());
            }
        }
    }

    /**
     * 参数校验
     *
     * @param
     */
    public void CheckKeyAddVOParam(KeyAddVO keyAddVO) throws BusinessException {
        if (!StringUtils.isEmpty(keyAddVO)) {
            List<String> validate = validate(keyAddVO);
            if (CollUtil.isNotEmpty(validate)) {
                throw new BusinessException(CodeEnum.PARAMETERS_OF_THE_ABNORMAL.getCode(), validate.toString());
            }
        }
    }

}
